﻿using System;
using System.Web;
using System.Web.Mvc;
using Until;
using Until.Log;

namespace Blog1._0
{
    /// <summary>
    /// 错误拦截
    /// </summary>
    public class HandlerErrorAttribute : HandleErrorAttribute
    {
        /// <summary>
        /// 控制器方法中出现异常，会调用该方法捕获异常
        /// </summary>
        /// <param name="context">提供使用</param>
        public override void OnException(ExceptionContext context)
        {
            WriteLog(context);
            base.OnException(context);
            context.ExceptionHandled = true;
            context.HttpContext.Response.StatusCode = 500;
            context.Result = new ContentResult { Content = new Result { type = false, msg = context.Exception.Message }.ToJson() };

        }
        /// <summary>
        /// 写入日志（log4net）
        /// </summary>
        private void WriteLog(ExceptionContext context)
        {
            if (context == null)
                return;
            Exception Error = context.Exception;
            LogMessage logMessage = new LogMessage();
            logMessage.OperationTime = DateTime.Now;
            logMessage.Url = HttpContext.Current.Request.RawUrl;
            logMessage.Class = context.Controller.ToString();
            logMessage.Ip = Net.Ip;
            logMessage.Host = Net.Host;
            logMessage.Browser = Net.Browser;
            logMessage.UserName = Current.GetEntity() == null ? "前台页面" : Current.GetEntity().LoginID + "（" + Current.GetEntity().UserName + "）";
            if (Error.InnerException == null)
            {
                logMessage.ExceptionInfo = Error.Message;
            }
            else
            {
                logMessage.ExceptionInfo = Error.InnerException.Message;
            }
            string strMessage = new LogFormat().ExceptionFormat(logMessage);
            Log4NetHelp.Error(strMessage);
        }
    }
}